define([
        //3.加载依赖的库
        'jquery',
        'knockout',
        'text!./update.html',
        'bootstrap',
        'director',
        'domReady!',
        'datatables.net-bs',
        // 'datatables.net-buttons',
        'datatables.net-autofill-bs',
        'net-jszip',
        'net-pdfmake',
        'datatables.net-buttons-bs',
        'datatables.net-colreorder',
        'datatables.net-rowreorder',
        'datatables.net-select',
        'datatables.net-scroller',
        'datatables.net-fixedHeader',
        // 'datatables.net-editor',
        'datatables.net-keyTable',
        'datatables.net-editor-bs',
        'datatables.net-responsive',
        'jstree',
    ],
    function ($, ko, template) {
        var viewModelUpdateType = {
            data: ko.observable({})
        };

        viewModelUpdateType.getAllInfo = function () {
            $('#update-grid').DataTable().ajax.reload(null,true);
        }

        var kj_nd;
        viewModelUpdateType.searchUpdateType = function () {
            kj_nd = $("#select-update-nd").val();
            if (kj_nd == "请选择会计年度") {
                kj_nd = "";
                return;
            }
            viewModelUpdateType.getAllInfo();
        }

        viewModelUpdateType.cancelUpdateTypeEdit = function () {
            $("#updatetype-id").val("");
            $("#update-edit-nd").get(0).selectedIndex = 0;
            $("#update-type").val("");
            $("#update-name").val("");
            $("#update-edit-nd").removeAttr("disabled");
            $("#update-type").removeAttr("disabled");
            $("#warn-text").css("display", "none");
            $("#edit-updatetype").modal("hide");
        }


        viewModelUpdateType.saveUpdateTypeEdit = function () {
            if (!checkInput()) {
                return;
            }
            var id = $("#updatetype-id").val();
            var update_nd = $("#update-edit-nd").val();
            var update_type = $("#update-type").val();
            var update_name = $("#update-name").val();
            $.ajax({
                url: $ctx + "/baseData/updateType/saveUpdateType",
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify({
                    id: id,
                    nd: update_nd,
                    updateType: update_type,
                    updateName: update_name,
                }),
                success: function (data) {
                    viewModelUpdateType.sendAjaxSuccess(data);
                }
            });
        }

        viewModelUpdateType.sendAjaxSuccess = function (data) {
            if (data.result == "success") {
                $("#save-success-new").css("display", "block");
                $("#save-success-new").fadeOut(3000);
                viewModelUpdateType.getAllInfo();
                viewModelUpdateType.cancelUpdateTypeEdit();
            }
            else {
                if (data.saveError != undefined) {
                    $("#edit-updatetype").modal("hide");
                    $("#error-text").text(data.saveError);
                    $("#error-notice").modal({backdrop: 'static', keyboard: false});
                } else {
                    $("#edit-updatetype").modal("hide");
                    $("#error-text").text(data.reason);
                    $("#error-notice").modal({backdrop: 'static', keyboard: false});
                }
            }
        }


        //删除界面 取消按钮 （有选择的时候）
        viewModelUpdateType.delete_updatetype_close = function () {
            $("#delete-updatetype-notice").modal("hide");
        }
        //删除界面 取消按钮 （无选择的时候）
        viewModelUpdateType.drop_updatetype_close = function () {
            $("#drop-updatetype-notice").modal("hide");
        }
        //编辑界面 取消按钮
        viewModelUpdateType.edit_updatetype_close = function () {
            $("#edit-updatetype-notice").modal("hide");
        }

        viewModelUpdateType.delete_updatetype = function () {
            selectRows = $('#update-grid').DataTable().rows('.selected');
            var idList=[];
            for (var i=0;i<selectRows.indexes().length;i++){
                idList[i] = selectRows.data()[i].id;
            }
            $.ajax({
                url: "/agcfs/baseData/updateType/delUpdateType",
                type: "POST",
                dataType: "json",
                data: {
                	ids: idList.join(',')
                },
                success: function (data) {
                	viewModelUpdateType.getAllInfo();
                	$("#delete-updatetype-notice").modal("hide");
                    if (data.result == "success") {
                    //    $("#delete-updatetype-notice").modal("hide");
                    //    viewModelUpdateType.getAllInfo();
                        //3秒消失
                        $("#save-success-new").css("display", "block");
                        $("#save-success-new").fadeOut(3000);
                    } else {
                        if (data.saveError != undefined) {
                        //    $("#delete-updatetype-notice").modal("hide");
                            $("#error-text").text(data.saveError);
                        //    $("#error-notice").modal({backdrop: 'static', keyboard: false});
                        } else {
                        //    $("#delete-updatetype-notice").modal("hide");
                            $("#error-text").text(data.reason);
                        }
                    }
                }
            });
        }

        viewModelUpdateType.checkUpdateTypeCode = function () {
            var code = $("#update-type").val();
            var patt = new RegExp("^\\d{1,9}$");
            var checkResult = patt.test(code);
            showWarnInfo(checkResult, "请输入正确调整类型代码：只能为数字且不能为空");
            return checkResult;
        }


        checkInput = function () {
            return viewModelUpdateType.checkUpdateTypeCode();
        }


        function showWarnInfo(checkResult, checkinfo) {
            if (!checkResult) {
                $("#warn-text").text(checkinfo);
                if ($('#warn-text').css("display") == "none") {
                    $("#warn-text").css("display", "inline-block");
                }
            } else {
                $("#warn-text").css("display", "none");
            }
        }


        addUpdateType = function () {
            $("#edit-updatetype").modal({backdrop: 'static', keyboard: false});
        }

        editUpdateType = function () {
        	selectRows = $('#update-grid').DataTable().rows('.selected');
            if ((selectRows.indexes().length ==0)||(selectRows.indexes().length >1)){
                $("#error-text").text("请选择一行编辑！");
                $("#edit-updatetype-notice").modal({backdrop: 'static', keyboard: false});
                return;
            };
            
            var selecteddata =selectRows.data()[0];
                $("#updatetype-id").val(selecteddata.id);
                $("#update-edit-nd").val(selecteddata.nd);
                $("#update-type").val(selecteddata.updateType);
                $("#update-name").val(selecteddata.updateName);
                $("#update-edit-nd").attr("disabled", "disabled");
                $("#update-type").attr("disabled", "disabled");
                $("#edit-updatetype").modal({backdrop: 'static', keyboard: false});
        }

        delUpdateType = function (index) {
            selectRows = $('#update-grid').DataTable().rows('.selected');
            if (selectRows.indexes().length ==0){
                $("#error-text").text("请选择要删除的数据！");
                $("#error-notice").modal({backdrop: 'static', keyboard: false});
                return;
            };
            $("#delete-updatetype-notice").modal({backdrop: 'static', keyboard: false});
//            var index = viewModelUpdateType.updateDataTable.getCurrentIndex();
//            if (index < 0) {
//                $("#drop-updatetype-notice").modal({backdrop: 'static', keyboard: false});
//            } else {
//                $("#delete-updatetype-notice").modal({backdrop: 'static', keyboard: false});
//            }

        }
        
//初始化Datatable表格
        initTable = function () {
            var editor;
            editor = new $.fn.dataTable.Editor({
                ajax: {
                    url: "baseData/updateType/getUpdateList",
                    dataType: "json",
                },
                table: "#update-grid",
                fields: [{
                    label: "年度:",
                    name: "nd"
                }, {
                    label: "调整类型:",
                    name: "updatetype"
                }, {
                    label: "调整名称:",
                    name: "updatename"
                }]
            });
            var table = $('#update-grid').DataTable({
            	language: {
                    "lengthMenu": "每页显示 _MENU_ 条记录",
                    "info": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                    "infoEmpty": "没有数据",
                    "infoFiltered": "(从 _MAX_ 条数据中检索)",
                    "zeroRecords": "没有检索到数据",
                    "search": "搜索:",
                    "paginate": {
                        "first": "首页",
                        "previous": "前一页",
                        "next": "后一页",
                        "last": "尾页"
                    },
                    select:{
                        rows:{
                            _:"%d行被选中",
                            0:""
                        }
                    }
                },
                colReorder: true,
                //rowReorder: true,
                lengthChange: false,
                retrieve:true,
                searching:false,
                // "bScrollCollapse": false,
                //      pagingType: 'full_numbers',
                paging: true,
                serverSide: false,
//                "dom": '<"wrapper"flipt>',
                ajax: {
                    url: "/agcfs/baseData/updateType/getUpdateList",
                    dataType: "json",
                    data: function (data) {
                        //添加额外的参数传给服务器
                        data.extra_search = kj_nd;
                    }
                },
                scrollX: true,
                scrollY: true,
                // scrollY:        200,
                //deferRender:    true,
                // scroller:       true,
//                fixedColumns: {        /*1.5.4 有bug,错位*/
//                    leftColumns: 2
//                },
//                 responsive: true,
                rowid: "id",
                columns: [
                    {   // Checkbox select column
                        data: null,
                        defaultContent: '',
                        className: 'select-checkbox',
                        orderable: false
                    },
                    {data: "nd"},
                    {data: "updateType"},
                    {data: "updateName"},
                ],
                order: [ 1, 'asc' ], //通过第一列排序 然后重绘表格并维持当前分页的信息

                select: {
                    style: 'multi', /* os,single,multi, multi+shift,api*/
                    selector: 'td.select-checkbox',
                }
            });
        };
//初始化年度
        initNd = function () {
            var searchNd = "#select-update-nd";
            var editNd = "#update-edit-nd";
            $.ajax({
                url: $ctx + "/baseData/updateType/getAllNd",
                type: "GET",
                dataType: "json",
                data: {},
                success: function (data) {
                	$(searchNd).html("");
                	$(editNd).html("");
                    var please_choice = '<option value="">请选择会计年度</option>';
                    $(searchNd).append(please_choice);
                    $(editNd).append(please_choice);
                    for (var i = 0; i < data.length; i++) {
                        var temp = '<option>' + data[i] + '</option>';
                        $(searchNd).append(temp);
                        $(editNd).append(temp);
                    }
                    kj_nd = $("#select-update-nd").val();
                    
                    initTable();
                }
            });
        };
        var init = function () {
            ko.cleanNode($('.content')[0]);
            app = u.createApp(
                {
                    el: '.content',
                    model: viewModelUpdateType
                }
            );
            initNd();
        };
        return {
            'model': viewModelUpdateType,
            "template": template, //模板
            'init': init
        };
    }
);

